package cn.com.unionlife.hy.system.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import cn.com.unionlife.hy.core.controller.BaseController;

public class LoginFilter implements Filter{
	
	private String key;
	private String redirectUrl;

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String url = request.getRequestURL().toString();
		HttpSession session = request.getSession();
		if (url.indexOf("login") < 0 && session.getAttribute(key) == null) {
			response.sendRedirect(request.getContextPath() + redirectUrl);
			return;
		} 
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		key = config.getInitParameter("user_key");
		redirectUrl = config.getInitParameter("redirect_url");
		if(StringUtils.isBlank(key)){
			key = BaseController.LOGINED_USER;
		}
		if(StringUtils.isBlank(redirectUrl)){
			redirectUrl = "/caslogin";
		}
	}

}
